﻿using System;
using System.Security.Cryptography;
using Grundy.Common;
using Grundy.Message;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Grundy.CryptographicServices.Tests
{
    [TestClass]
    public class Sha256MacProviderTests
    {
        private string key;

        private const string MESSAGE = "This is the test data!";

        [TestInitialize]
        public void Setup()
        {
            var buffer = new byte[64];
            new RNGCryptoServiceProvider().GetNonZeroBytes(buffer);
            key = buffer.ToHexadecimalString();
        }

        [TestMethod]
        public void Should_Set_ProviderString_On_Container()
        {
            var payload = new ProcessorIdentifier { Value = MESSAGE };
            Guid customerId = Guid.NewGuid();
            string customerName = "Some_Customer";
            var sha256MacProvider = new Sha256MacProvider(key, customerId, customerName);
            var container = sha256MacProvider.Sign(payload);
            var providerInfo = container.Provider.Split(new [] {','});
            Assert.AreEqual(providerInfo[0], "Sha256MacProvider");
            Assert.AreEqual(providerInfo[1], customerId.ToString());
            Assert.AreEqual(providerInfo[2], customerName);
        }

        [TestMethod]
        public void Should_Not_Be_Able_To_Verify_Container()
        {
            var payload = new ProcessorIdentifier { Value = MESSAGE };
            Guid customerId = Guid.NewGuid();
            string customerName = "Some_Customer";
            var sha256MacProvider = new Sha256MacProvider(key, customerId, customerName);
            var container = sha256MacProvider.Sign(payload);
            container.Provider = "RsaProvider";
            var verifiedPayload = sha256MacProvider.Verify<Identifier>(container);
            Assert.IsNull(verifiedPayload);
        }

        [TestMethod]
        public void Should_Sign_And_Verify_Data()
        {
            var payload = new ProcessorIdentifier { Value = MESSAGE };
            var sha256MacProvider = new Sha256MacProvider(key);

            var container = sha256MacProvider.Sign(payload);
            var verifiedPayload = sha256MacProvider.Verify<Identifier>(container);
            Assert.AreEqual(verifiedPayload.Value, MESSAGE);
        }

        [TestMethod]
        public void Should_Not_Sign_And_Verify_Data()
        {
            var payload = new ProcessorIdentifier { Value = MESSAGE };
            var sha256MacProvider = new Sha256MacProvider(key);

            var container = sha256MacProvider.Sign(payload);
            container.Signature = container.Signature.Replace('1', '2');
            var verifiedPayload = sha256MacProvider.Verify<Identifier>(container);
            Assert.IsNull(verifiedPayload);
        }
    }
}